package com.ys.erp.stage_marketing_service.service;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.ys.erp.common.enums.EnableEnum;
import com.ys.erp.common.enums.old.StatusOldEnum;
import com.ys.erp.common.enums.old.TypeOldEnum;
import com.ys.erp.common.util.MoneyUtil;

import com.ys.erp.common.util.YsThread;
import com.ys.erp.entity.data.bean.*;
import com.ys.erp.entity.service.*;
import com.ys.erp.framework.bean.dto.StageEmpDTO;
import com.ys.erp.framework.exception.YsException;
import com.ys.erp.framework.response.AbstractResponseCode;
import com.ys.erp.framework.response.PageDTO;
import com.ys.erp.stage_marketing_service.bean.condition.CouponsCondition;
import com.ys.erp.stage_marketing_service.bean.vo.CouponSendRecordVO;
import com.ys.erp.stage_marketing_service.bean.vo.CouponStatisticsVO;
import com.ys.erp.stage_marketing_service.bean.vo.CouponVO;
import com.ys.erp.stage_marketing_service.utils.CouponNotificationUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author lwj
 * @date 2023/5/31
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CouponsService {

    private final IEventLogService iEventLogService;

    private final ICouponService iCouponService;

    private final IGoodsSpecsService iGoodsSpecsService;

    private final IGoodsService iGoodsService;

    private final IUserService iUserService;

    private final IUserCouponService iUserCouponService;

    private final IMallHomeActivityService iMallHomeActivityService;

    private final IMallHomeActivityCouponsService iMallHomeActivityCouponsService;

    private final IEmployeeService iEmployeeService;

    private final CouponNotificationUtil couponNotificationUtil;


    public PageDTO<CouponVO> pageCoupon(StageEmpDTO emp, CouponsCondition.PageCouponCon con) {
        Page<Coupon> couponPage = new Page<>(con.getCurrent(), con.getSize());
        QueryWrapper<Coupon> couponQw = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(con.getCouponName())) {
            couponQw.lambda().like(Coupon::getCouponName, con.getCouponName());
        }
        couponQw.lambda().orderByDesc(Coupon::getId);
        Page<Coupon> page = iCouponService.page(couponPage, couponQw);
        List<CouponVO> collect = page.getRecords().stream()
                .map(it -> {
                    CouponVO couponVO = new CouponVO();
                    BeanUtils.copyProperties(it, couponVO);
                    couponVO.setMinFee(MoneyUtil.long2Str(it.getMinFee()));
                    couponVO.setPreferentialMoney(MoneyUtil.long2Str(it.getPreferentialMoney()));
                    return couponVO;
                }).collect(Collectors.toList());
        return new PageDTO<>(page.getCurrent(), page.getTotal(), collect);
    }

    public void addOrUpdateCoupon(StageEmpDTO emp, CouponsCondition.AddOrUpdateCouponCon con) {
        addCouponValid(con);
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(con, coupon);
        if (con.getValidType() == TypeOldEnum.COUPON_VALID_TIME.getType()) {
            coupon.setValidStartTime(con.getValidStartTime().plusDays(1).atStartOfDay());
            coupon.setValidEndTime(con.getValidEndTime().plusDays(1).atStartOfDay());
        }
        coupon.setSuitGoodsIds(JSONArray.toJSONString(con.getSuitGoodsIds()));
        coupon.setSuitGoodsCategoryIds(JSONArray.toJSONString(con.getSuitGoodsCategoryIds()));
        coupon.setGiveGoodsSpecsIds(JSONArray.toJSONString(con.getGiveGoodsSpecsIds()));
        coupon.setMinFee(MoneyUtil.str2Long(con.getMinFee()));
        coupon.setPreferentialMoney(MoneyUtil.str2Long(con.getPreferentialMoney()));
        if (ObjectUtil.isEmpty(con.getId())) {
            //新增
            iCouponService.save(coupon);
            //增加操作记录
            iEventLogService.insertEvent(emp, "增加" + con.getCouponName() + "优惠券", coupon.getId(), EnableEnum.NO.getEnable(), JSONObject.toJSONString(con));
            //增加日志
            return;
        }
        Coupon dbCoupon = iCouponService.getById(con.getId());
        if (ObjectUtil.isEmpty(dbCoupon)) {
            throw new YsException(AbstractResponseCode.INFO_NULL);
        }
        coupon.setId(dbCoupon.getId());
        coupon.setVersion(dbCoupon.getVersion());
        coupon.setCreateTime(dbCoupon.getCreateTime());
        iCouponService.updateById(coupon);
        iEventLogService.insertEvent(emp, "编辑" + con.getCouponName() + "优惠券", coupon.getId(), EnableEnum.NO.getEnable(), JSONObject.toJSONString(con));
    }


    public CouponVO getCouponDetail(Long couponId) {
        if (ObjectUtil.isEmpty(couponId)) {
            throw new YsException(AbstractResponseCode.INFO_NULL);
        }
        Coupon coupon = iCouponService.getById(couponId);
        if (ObjectUtil.isEmpty(coupon)) {
            throw new YsException(AbstractResponseCode.INFO_NULL);
        }
        CouponVO couponVO = new CouponVO();
        BeanUtils.copyProperties(coupon, couponVO);
        couponVO.setGiveGoodsSpecsIds(JSONArray.parseArray(coupon.getGiveGoodsSpecsIds(), Long.class));
        couponVO.setSuitGoodsIds(JSONArray.parseArray(coupon.getSuitGoodsIds(), Long.class));
        couponVO.setSuitGoodsCategoryIds(JSONArray.parseArray(coupon.getSuitGoodsCategoryIds(), Long.class));
        couponVO.setMinFee(MoneyUtil.long2Str(coupon.getMinFee()));
        couponVO.setPreferentialMoney(MoneyUtil.long2Str(coupon.getPreferentialMoney()));
        //查询
        if (coupon.getCouponType() == TypeOldEnum.COUPON_GIVE.getType()) {
            HashSet<Long> goodsSpecsIds =
                    new HashSet<>(JSONArray.parseArray(coupon.getGiveGoodsSpecsIds(), Long.class));
            List<GoodsSpecs> goodsSpecs = iGoodsSpecsService.listByIds(goodsSpecsIds);
            List<CouponVO.CouponGoodsAndSpecsVO> specsVOList = goodsSpecs.stream()
                    .map(it -> {
                        CouponVO.CouponGoodsAndSpecsVO specsVO = new CouponVO.CouponGoodsAndSpecsVO();
                        specsVO.setId(it.getId());
                        specsVO.setPic(it.getPic());
                        String attrMap = it.getGoodsSpecs();
                        List<OrderGoods.KeyValueDTO> keyValueList = JSONArray.parseArray(attrMap, OrderGoods.KeyValueDTO.class);
                        StringBuilder buffer = new StringBuilder();
                        for (OrderGoods.KeyValueDTO dto : keyValueList) {
                            buffer.append(dto.getKey()).append(":").append(dto.getValue());
                        }
                        specsVO.setName(buffer.toString());
                        return specsVO;
                    }).collect(Collectors.toList());
            couponVO.setGiveSpecsList(specsVOList);
        }
        if (coupon.getSuitScopeType() == TypeOldEnum.COUPON_SUIT_GOODS.getType()) {
            HashSet<Long> longs = new HashSet<>(JSONArray.parseArray(coupon.getSuitGoodsIds(), Long.class));
            List<Goods> goods = iGoodsService.listByIds(longs);
            List<CouponVO.CouponGoodsAndSpecsVO> collect = goods.stream()
                    .map(it -> {
                        CouponVO.CouponGoodsAndSpecsVO specsVO = new CouponVO.CouponGoodsAndSpecsVO();
                        List<String> strings = JSONArray.parseArray(it.getGoodsBanner(), String.class);
                        specsVO.setId(it.getId());
                        specsVO.setPic(strings.get(0));
                        specsVO.setName(it.getGoodsName());
                        return specsVO;
                    }).collect(Collectors.toList());
            couponVO.setSuitGoodsList(collect);
        }
        return couponVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public void grantCoupon(StageEmpDTO emp, CouponsCondition.GrantCouponCon con) {
        if (con.getGrantType() == 0 && ObjectUtil.isEmpty(con.getCouponId())) {
            throw new YsException(AbstractResponseCode.INFO_NULL);
        }
        if (con.getGrantType() == 1 && con.getUserIds().isEmpty()) {
            throw new YsException(AbstractResponseCode.INFO_NULL);
        }
        Coupon coupon = iCouponService.getById(con.getCouponId());
        if (ObjectUtil.isEmpty(coupon)) {
            throw new YsException(AbstractResponseCode.INFO_NULL);
        }
        List<User> userList = new ArrayList<>();
        QueryWrapper<User> userQw = new QueryWrapper<>();
        if (con.getGrantType() == 0) {
            userQw.lambda().eq(User::getVipLevelId, con.getMemberId());
            List<User> list = iUserService.list(userQw);
            userList.addAll(list);
        } else {
            //查询用户集合
            List<Long> userIds = con.getUserIds();
            userQw.lambda().in(User::getId, userIds);
            List<User> list = iUserService.list(userQw);
            userList.addAll(list);
        }
        ArrayList<UserCoupon> userCoupons = new ArrayList<>();
        for (User user : userList) {
            for (int i = 0; i < con.getQuantity(); i++) {
                UserCoupon userCoupon = new UserCoupon();
                userCoupon.setUserId(user.getId());
                userCoupon.setCouponId(coupon.getId());
                userCoupon.setSourceType(UserCoupon.Enums.SYSTEM_COUPON.toString());
                userCoupon.setSourceId(emp.getId());
                userCoupon.setCouponStatus(StatusOldEnum.COUPON_UN_USE.getStatus());
                userCoupon.setGetTime(LocalDateTime.now());
                if (coupon.getValidType() == TypeOldEnum.COUPON_VALID_DAYS.getType()) {
                    LocalDate startTime = LocalDate.now();
                    LocalDate endTime = startTime.plusDays(coupon.getValidDays());
                    userCoupon.setValidStartTime(startTime.atStartOfDay());
                    userCoupon.setValidEndTime(endTime.atStartOfDay().plusDays(1));
                } else if (coupon.getValidType() == TypeOldEnum.COUPON_VALID_TIME.getType()) {
                    userCoupon.setValidStartTime(coupon.getValidStartTime());
                    userCoupon.setValidEndTime(coupon.getValidEndTime());
                }
                userCoupon.setEmpId(emp.getId());
                userCoupon.setEmpName(emp.getRealName());
                userCoupons.add(userCoupon);
            }
            iEventLogService.insertEvent(emp, "发放" + con.getQuantity() + "张优惠券给" + user.getPhone(), coupon.getId(), EnableEnum.NO.getEnable(), JSONObject.toJSONString(con));
            
            // 发送优惠券发放通知
            couponNotificationUtil.sendCouponGrantNotification(user, coupon, con.getQuantity(), emp.getRealName(), con.getGrantType());
        }
        List<List<UserCoupon>> lists = ListUtil.split(userCoupons, 2500);
        for (List<UserCoupon> userCouponsList : lists) {
            iUserCouponService.saveBatch(userCouponsList);
        }
    }

    public CouponStatisticsVO couponStatistics(CouponsCondition.CouponStatisticsCon con) {

        //创建查询
        QueryWrapper<UserCoupon> userCouponQw = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(con.getCouponName())) {
            LambdaQueryWrapper<Coupon> couponQw = new LambdaQueryWrapper<>();
            couponQw.like(Coupon::getCouponName, con.getCouponName());
            List<Long> couponIdList = iCouponService.list(couponQw).stream().map(Coupon::getId).toList();
            if (couponIdList.isEmpty()) {
                userCouponQw.lambda().in(UserCoupon::getCouponId, "-1");
            } else {
                userCouponQw.lambda().in(UserCoupon::getCouponId, couponIdList);
            }
        }

        if (ObjectUtil.isNotEmpty(con.getActivityId())) {
            MallHomeActivity activity = iMallHomeActivityService.getById(con.getActivityId());
            if (activity == null) {
                userCouponQw.lambda().in(UserCoupon::getCouponId, "-1");
            } else {
                LambdaQueryWrapper<MallHomeActivityCoupons> couponQw = new LambdaQueryWrapper<>();
                couponQw.eq(MallHomeActivityCoupons::getActivityNo, activity.getNo());
                List<Long> couponList = iMallHomeActivityCouponsService.list(couponQw).stream().map(MallHomeActivityCoupons::getCouponsId).toList();
                if (couponList.isEmpty()) {
                    userCouponQw.lambda().in(UserCoupon::getCouponId, "-1");
                }
                userCouponQw.lambda().in(UserCoupon::getCouponId, couponList);
            }
        }
        if (ObjectUtil.isNotEmpty(con.getSendMethod())) {
            userCouponQw.lambda().eq(UserCoupon::getSourceType, con.getSendMethod());
        }
        CompletableFuture<HashMap<Long, List<String>>> activityNameMapFuture = YsThread.execute(() -> {
            List<MallHomeActivityCoupons> mallHomeActivityCoupons = iMallHomeActivityCouponsService.list();
            if (mallHomeActivityCoupons.isEmpty()) {
                return new HashMap<>();
            }
            Set<String> activityNoSet = mallHomeActivityCoupons.stream().map(MallHomeActivityCoupons::getActivityNo).collect(Collectors.toSet());
            LambdaQueryWrapper<MallHomeActivity> activityQw = new LambdaQueryWrapper<>();
            activityQw.in(MallHomeActivity::getNo, activityNoSet);
            List<MallHomeActivity> activityList = iMallHomeActivityService.list(activityQw);
            if (activityList.isEmpty()) {
                return new HashMap<>();
            }
            Map<String, String> activityNoMap = activityList.stream().collect(Collectors.toMap(MallHomeActivity::getNo, MallHomeActivity::getActivityName));
            Map<Long, List<MallHomeActivityCoupons>> activityCouponMap = mallHomeActivityCoupons.stream()
                    .collect(Collectors.groupingBy(MallHomeActivityCoupons::getCouponsId));
            HashMap<Long, List<String>> result = new HashMap<>();
            for (Map.Entry<Long, List<MallHomeActivityCoupons>> entry : activityCouponMap.entrySet()) {
                List<MallHomeActivityCoupons> couponsList = entry.getValue();
                ArrayList<String> activityNameList = new ArrayList<>();
                for (MallHomeActivityCoupons coupons : couponsList) {
                    String activityName = activityNoMap.get(coupons.getActivityNo());
                    activityNameList.add(activityName);
                }
                result.put(entry.getKey(), activityNameList);
            }
            return result;
        });
        Map<Long, List<UserCoupon>> userCouponMap = iUserCouponService.list(userCouponQw).stream()
                .collect(Collectors.groupingBy(UserCoupon::getCouponId));
        Map<Long, Coupon> couponMap = iCouponService.list().stream()
                .collect(Collectors.toMap(Coupon::getId, coupon -> coupon));
        CouponStatisticsVO couponStatisticsVO = new CouponStatisticsVO();
        couponStatisticsVO.setTotalCount(new CouponStatisticsVO.NumberStatisticsVO());
        couponStatisticsVO.setUnUseCount(new CouponStatisticsVO.NumberStatisticsVO());
        couponStatisticsVO.setUsedCount(new CouponStatisticsVO.NumberStatisticsVO());
        couponStatisticsVO.setTimeoutCount(new CouponStatisticsVO.NumberStatisticsVO());
        ArrayList<CouponStatisticsVO.CouponInfoStatisticsVO> infoList = new ArrayList<>();
        HashMap<Long, List<String>> activityNameMap = activityNameMapFuture.join();
        for (Map.Entry<Long, Coupon> entry : couponMap.entrySet()) {
            Long k = entry.getKey();
            Coupon v = entry.getValue();
            CouponStatisticsVO.CouponInfoStatisticsVO infoVo = new CouponStatisticsVO.CouponInfoStatisticsVO();
            List<UserCoupon> userCouponList = userCouponMap.get(k);
            infoVo.setId(k);
            infoVo.setCouponName(v.getCouponName());
            infoVo.setTotalCount(userCouponList == null ? 0 : userCouponList.size());
            infoVo.setUnUseCount(0);
            infoVo.setUsedCount(0);
            infoVo.setTimeoutCount(0);
            List<String> activityName = activityNameMap.get(v.getId());
            infoVo.setActivityNameList(activityName);
            if (userCouponMap.containsKey(k)) {
                assert userCouponList != null;
                couponStatisticsVO.getTotalCount().setTotalCount(couponStatisticsVO.getTotalCount().getTotalCount() + userCouponList.size());
                couponStatisticsVO.getTotalCount().setActivityNumber((int) (couponStatisticsVO.getTotalCount().getActivityNumber() +
                        userCouponList.stream().filter(it -> it.getSourceType().equals(UserCoupon.Enums.ACTIVITY_COUPON.name())).count()));
                couponStatisticsVO.getTotalCount().setSystemNumber((int) (couponStatisticsVO.getTotalCount().getSystemNumber() +
                        userCouponList.stream().filter(it -> it.getSourceType().equals(UserCoupon.Enums.SYSTEM_COUPON.name())).count()));

                for (UserCoupon userCoupon : userCouponList) {
                    if (userCoupon.getCouponStatus() == StatusOldEnum.COUPON_UN_USE.getStatus()) {
                        couponStatisticsVO.getUnUseCount().setTotalCount(couponStatisticsVO.getUnUseCount().getTotalCount() + 1);
                        if (userCoupon.getSourceType().equals(UserCoupon.Enums.ACTIVITY_COUPON.name())) {
                            couponStatisticsVO.getUnUseCount().setActivityNumber(couponStatisticsVO.getUnUseCount().getActivityNumber() + 1);
                        } else {
                            couponStatisticsVO.getUnUseCount().setSystemNumber((couponStatisticsVO.getUnUseCount().getSystemNumber() + 1));
                        }
                        infoVo.setUnUseCount(infoVo.getUnUseCount() + 1);
                        continue;
                    }
                    if (userCoupon.getCouponStatus() == StatusOldEnum.COUPON_USED.getStatus()) {
                        couponStatisticsVO.getUsedCount().setTotalCount(couponStatisticsVO.getUsedCount().getTotalCount() + 1);
                        if (userCoupon.getSourceType().equals(UserCoupon.Enums.ACTIVITY_COUPON.name())) {
                            couponStatisticsVO.getUsedCount().setActivityNumber(couponStatisticsVO.getUsedCount().getActivityNumber() + 1);
                        } else {
                            couponStatisticsVO.getUsedCount().setSystemNumber((couponStatisticsVO.getUsedCount().getSystemNumber() + 1));
                        }
                        infoVo.setUsedCount(infoVo.getUsedCount() + 1);
                        continue;
                    }
                    couponStatisticsVO.getTimeoutCount().setTotalCount(couponStatisticsVO.getTimeoutCount().getTotalCount() + 1);
                    if (userCoupon.getSourceType().equals(UserCoupon.Enums.ACTIVITY_COUPON.name())) {
                        couponStatisticsVO.getTimeoutCount().setActivityNumber(couponStatisticsVO.getTimeoutCount().getActivityNumber() + 1);
                    } else {
                        couponStatisticsVO.getTimeoutCount().setSystemNumber((couponStatisticsVO.getTimeoutCount().getSystemNumber() + 1));
                    }
                    infoVo.setTimeoutCount(infoVo.getTimeoutCount() + 1);
                }
            }

            infoList.add(infoVo);
        }

        couponStatisticsVO.setCouponInfoStatisticsList(infoList);
        return couponStatisticsVO;
    }


    public PageDTO<CouponSendRecordVO> pageCouponSendRecord(CouponsCondition.PageCouponSentRecordCon con) {
        //创建查询
        QueryWrapper<UserCoupon> userCouponQw = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(con.getCouponId())) {
            userCouponQw.lambda().eq(UserCoupon::getCouponId, con.getCouponId());
        }
        userCouponQw.lambda().orderByDesc(UserCoupon::getGetTime);
        Page<UserCoupon> userCouponPage = new Page<>(con.getCurrent(), con.getSize());
        //查询
        Page<UserCoupon> page = iUserCouponService.page(userCouponPage, userCouponQw);
        if (page.getRecords().isEmpty()) {
            return new PageDTO<>(1L, 0L, new ArrayList<>());
        }
        Map<Long, String> activityNameMap = new HashMap<>();
        List<Long> activityIdList = page.getRecords().stream()
                .filter(it -> it.getSourceType().equals(UserCoupon.Enums.ACTIVITY_COUPON.name()))
                .map(UserCoupon::getSourceId).toList();
        if (!activityIdList.isEmpty()) {
            QueryWrapper<MallHomeActivity> activityQw = new QueryWrapper<>();
            activityQw.lambda().select(MallHomeActivity::getId, MallHomeActivity::getActivityName);
            activityQw.lambda().in(MallHomeActivity::getId, activityIdList);
            activityNameMap = iMallHomeActivityService.list(activityQw).stream()
                    .collect(Collectors.toMap(MallHomeActivity::getId, MallHomeActivity::getActivityName));
        } else {
            activityNameMap = new HashMap<>();
        }
        Map<Long, String> empMap = new HashMap<>();
        List<Long> systemIdList = page.getRecords()
                .stream()
                .filter(it -> it.getSourceType().equals(UserCoupon.Enums.SYSTEM_COUPON.name()))
                .map(UserCoupon::getSourceId).toList();
        if (!systemIdList.isEmpty()) {
            QueryWrapper<Employee> empQw = new QueryWrapper<>();
            empQw.lambda().select(Employee::getId, Employee::getRealName);
            empQw.lambda().in(Employee::getId, systemIdList);
            empMap = iEmployeeService.list(empQw).stream()
                    .collect(Collectors.toMap(Employee::getId, Employee::getRealName));
        } else {
            empMap = new HashMap<>();
        }
        List<Long> userIds = page.getRecords().stream().map(UserCoupon::getUserId).collect(Collectors.toList());
        List<Long> couponIds = page.getRecords().stream().map(UserCoupon::getCouponId).collect(Collectors.toList());
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.lambda().select(User::getId, User::getNickName);
        userQw.lambda().in(User::getId, userIds);
        Map<Long, User> userMap = iUserService.list(userQw).stream()
                .collect(Collectors.toMap(User::getId, it -> it));
        Map<Long, Coupon> couponMap = iCouponService.listByIds(couponIds).stream()
                .collect(Collectors.toMap(Coupon::getId, it -> it));
        List<CouponSendRecordVO> result = new ArrayList<>();
        for (UserCoupon it : page.getRecords()) {
            User user = userMap.get(it.getUserId());
            Coupon coupon = couponMap.get(it.getCouponId());
            CouponSendRecordVO vo = new CouponSendRecordVO();
            vo.setCouponName(coupon.getCouponName());
            vo.setUserName(user.getNickName());
            vo.setUserId(user.getId());
            vo.setSendTime(it.getGetTime());
            vo.setValidStartTime(it.getValidStartTime());
            vo.setValidEndTime(it.getValidEndTime());
            vo.setCouponStatus(it.getCouponStatus());
            vo.setEmpName(it.getEmpName());
            if (it.getSourceType().equals(UserCoupon.Enums.ACTIVITY_COUPON.name())) {
                vo.setIssueMothed(UserCoupon.Enums.ACTIVITY_COUPON.name());
                vo.setIssueName(activityNameMap.get(it.getSourceId()));
                vo.setRemark("活动发放");
            } else {
                vo.setIssueMothed(UserCoupon.Enums.SYSTEM_COUPON.name());
                vo.setIssueName(empMap.get(it.getSourceId()));
                vo.setRemark("手动发放");
            }
            result.add(vo);
        }
        return new PageDTO<>(page.getCurrent(), page.getTotal(), result);
    }


    public void addCouponValid(CouponsCondition.AddOrUpdateCouponCon con) {
        if (con.getCouponType() == TypeOldEnum.COUPON_ADD_REDUCE.getType()
                && (ObjectUtil.isEmpty(con.getPreferentialMoney())
                || MoneyUtil.str2Long(con.getPreferentialMoney()) <= 0)) {
            throw new YsException(AbstractResponseCode.VALID_ERROR);
        }
        if (con.getCouponType() == TypeOldEnum.COUPON_DISCOUNT.getType()
                && ObjectUtil.isEmpty(con.getDiscount())) {
            throw new YsException(AbstractResponseCode.VALID_ERROR);
        }
        if (con.getCouponType() == TypeOldEnum.COUPON_GIVE.getType()
                && con.getGiveGoodsSpecsIds().isEmpty()) {
            throw new YsException(AbstractResponseCode.VALID_ERROR);
        }
        if (con.getSuitScopeType() == TypeOldEnum.COUPON_SUIT_GOODS_CATEGORY.getType()
                && con.getSuitGoodsCategoryIds().isEmpty()) {
            throw new YsException(AbstractResponseCode.VALID_ERROR);
        }
        if (con.getSuitScopeType() == TypeOldEnum.COUPON_SUIT_GOODS.getType()
                && con.getSuitGoodsIds().isEmpty()) {
            throw new YsException(AbstractResponseCode.VALID_ERROR);
        }
        if (con.getValidType() == TypeOldEnum.COUPON_VALID_DAYS.getType()
                && (ObjectUtil.isEmpty(con.getValidDays())
                || con.getValidDays() < 0)) {
            throw new YsException(AbstractResponseCode.VALID_ERROR);
        }
        if (con.getValidType() == TypeOldEnum.COUPON_VALID_TIME.getType()
                && (ObjectUtil.isEmpty(con.getValidStartTime())
                || ObjectUtil.isEmpty(con.getValidEndTime()))) {
            throw new YsException(AbstractResponseCode.VALID_ERROR);
        }
    }

}
